﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace ARPGDemo.Skill
{
    /// <summary>
    /// 释放器配置工厂
    /// </summary>
    public class DeployerConfigFactory
    {
        //对象池
        private static Dictionary<string, object> cache;
        static DeployerConfigFactory()
        {
            cache = new Dictionary<string, object>();
        }
        public static IAttackSelector CreatAttackSelector(SkillData data)
        {
            string classNameAll = "ARPGDemo.Skill." + data.selectorType + "AttackSelector";
            //Type type = Type.GetType(classNameAll);
            //return Activator.CreateInstance(type) as IAttackSelector;
            return CreateObject<IAttackSelector>(classNameAll);
        }

        public static List<IImpact> CreatImpact(SkillData data)
        {
            List<IImpact> list = new List<IImpact>(data.impactType.Length);
            for (int i = 0; i < data.impactType.Length; i++)
            {
                string classNameAll = "ARPGDemo.Skill." + data.impactType[i] + "Impact";
                //Type type = Type.GetType(classNameAll);
                //list.Add(Activator.CreateInstance(type) as IImpact);
                list.Add(CreateObject<IImpact>(classNameAll));
            }
            return list;
        }
        /// <summary>
        /// 对象池
        /// 可能存在的bug：一个技能伤害还在计算，释放另一个技能，导致前一个技能持续时间改变，则前技能停止伤害
        /// 解决方法：不要伤害共用的技能数据，使用局部变量读取技能数据，详见DamageImpact中修改RepeatAttack和Attack方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="classNameAll"></param>
        /// <returns></returns>
        private static T CreateObject<T>(string classNameAll) where T:class
        {
            //Type type = Type.GetType(classNameAll);
            //return Activator.CreateInstance(type) as T;

            //先判断池中是否具有可以使用的对象
            if (!cache.ContainsKey(classNameAll))
            {
                //如果没有则创建对象并添加到池中
                //Debug.Log("反射创建对象");
                Type type = Type.GetType(classNameAll);
                cache.Add(classNameAll,Activator.CreateInstance(type));
            }
           
            return cache[classNameAll] as T;
            //从池中返回对象
        }
}
}

